from masonite.controllers import Controller
from masonite.views import View
from masonite.request import Request
from masonite.response import Response
from app.traits.MyControllerTrait import MyControllerTrait
from app.traits.MyModelTrait import MyModelTrait
from app.models.AdminPermission import AdminPermission
from masonite.facades import Session
from app.models.AdminActionLog import AdminActionLog
from app.my_package.MyPackage import MyValidator


class AdminPermissionController(Controller):
    uri = "/admin/permission"
    temp = 'admin.permission'

    def index(self, view: View):
        uri = self.uri + '/index'
        data = {
            'uri': self.uri,
            'title': MyControllerTrait.get_permission_title(uri),
            'menus': MyControllerTrait.get_menu_nav(uri)
        }
        return view.render(self.temp + ".index", data)

    def show(self, request: Request, response: Response):
        page = request.input("page", 1)
        limit = request.input("limit", 10)
        title = request.input("title")
        uri = request.input("uri")

        pids = AdminPermission.get_title_of_pid()
        table = AdminPermission.get_table_name()
        where = ''
        order = 'id DESC'
        total, admin_permissions = MyModelTrait.search_for_show(table, where, '*', page, limit, order)
        if admin_permissions is not None:
            for index, admin_permission in enumerate(admin_permissions):
                admin_permissions[index]['created_at'] = MyControllerTrait.time_format_conversion(admin_permission['created_at'])
                admin_permissions[index]['updated_at'] = MyControllerTrait.time_format_conversion(admin_permission['updated_at'])
                if admin_permission['pid'] in pids:
                    admin_permissions[index]['pid'] = pids[admin_permission['pid']]
                else:
                    admin_permissions[index]['pid'] = '根目录'

        data = {
            'code': 0,
            'message': 'success',
            'total': total,
            'data': admin_permissions
        }
        return response.json(data)

    def create(self, view: View):
        data = {
            'title': MyControllerTrait.get_permission_title(self.uri + '/create'),
            'uri': self.uri,
            'pids': AdminPermission.get_all_pid(),
        }
        return view.render(self.temp + ".create", data)

    def edit(self, request: Request, response:Response, view: View):
        permission_id = request.input("permission_id")
        b, m = MyValidator.is_integer(int(permission_id))
        if b is False:
            return response.redirect(self.uri+'/index', status=302)

        admin_permission = AdminPermission.where('id', permission_id).first()
        if admin_permission is None:
            return response.redirect(location=self.uri + "/index", status=302)

        data = {
            'title': MyControllerTrait.get_permission_title(self.uri + '/edit'),
            'uri': self.uri,
            'pids': AdminPermission.get_all_pid(),
            'permission_id': admin_permission.pid,
            'data': admin_permission,
        }
        return view.render(self.temp + ".edit", data)

    def store(self, request: Request, response: Response):
        title = request.input('title')
        uri = request.input('uri')
        pid = request.input('pid')

        b, m = MyValidator.ch_alpha_num(title)
        if b is False:
            return response.json({'code': 0, 'message': '名称' + m})
        b, m = MyValidator.between(title, 1, 100)
        if b is False:
            return response.json({'code': 0, 'message': '名称' + m})
        b, m = MyValidator.uri(uri)
        if b is False:
            return response.json({'code': 0, 'message': '链接' + m})
        b, m = MyValidator.between(uri, 1, 100)
        if b is False:
            return response.json({'code': 0, 'message': '链接' + m})
        b, m = MyValidator.is_integer(int(pid))
        if b is False:
            return response.json({'code': 0, 'message': '上级目录' + m})

        admin_permission = AdminPermission.where('uri', uri).first()
        if admin_permission is not None:
            return response.json({'code':0, 'message':'链接 {0} 已存在'.format(uri)})
        if int(pid) not in AdminPermission.get_all_pid() and int(pid) != 0:
            return response.json({'code':0, 'message':'未知上级目录'})

        path = AdminPermission.generate_path(pid)
        AdminPermission.generate_log(title, uri, pid, path)
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}({1})".format(title, uri)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code':1, 'message':'成功'})

    def update(self, request: Request, response: Response):
        permission_id = request.input('permission_id')
        title = request.input("title")
        uri = request.input('uri')
        pid = request.input('pid')

        b, m = MyValidator.ch_alpha_num(title)
        if b is False:
            return response.json({'code': 0, 'message': '名称' + m})
        b, m = MyValidator.between(title, 1, 100)
        if b is False:
            return response.json({'code': 0, 'message': '名称' + m})
        b, m = MyValidator.uri(uri)
        if b is False:
            return response.json({'code': 0, 'message': '链接' + m})
        b, m = MyValidator.between(title, 1, 100)
        if b is False:
            return response.json({'code': 0, 'message': '链接' + m})
        b, m = MyValidator.is_integer(int(pid))
        if b is False:
            return response.json({'code': 0, 'message': '上级目录' + m})
        b, m = MyValidator.is_integer(int(permission_id))
        if b is False:
            return response.json({'code': 0, 'message': 'id' + m})

        admin_permission = AdminPermission.where('id', permission_id).first()
        if admin_permission is None:
            return response.json({'code':0, 'message':'未知权限'})

        data = {}
        if admin_permission['title'] != title:
            data['title'] = title
        if admin_permission['uri'] != uri:
            data['uri'] = uri
        if admin_permission['pid'] != int(pid):
            data['pid'] = pid
        if len(data) > 0:
            admin_permission.update(data)
        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}({1})".format(admin_permission.title, admin_permission.uri)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        return response.json({'code':1, 'message':'成功'})

    def destroy(self, request: Request, response: Response):
        permission_id = request.input('permission_id')
        b, m = MyValidator.is_integer(int(permission_id))
        if b is False:
            return response.json({'code': 0, 'message': 'id' + m})

        admin_permission = AdminPermission.where('id', permission_id).first()
        if admin_permission is None:
            return response.json({'code':0, 'message':'未知权限'})

        remark = MyControllerTrait.get_permission_title(request.get_path()) + ":{0}({1})".format(admin_permission.title, admin_permission.uri)
        AdminActionLog.generate_log(Session.get('admin_user')['id'], request.get_path(), request.ip(), remark)
        # 删除子权限
        AdminPermission.where('pid', permission_id).delete()
        admin_permission.delete()
        return response.json({'code':1, 'message':'成功'})
